package simple.tree;

import struct.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 145. 二叉树的后序遍历
 * @author 刘学松
 * @date 2021-12-26 3:08
 */
public class 二叉树的后序遍历 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        preorder(list, root);
        return list;
    }

    public void preorder(List<Integer> list, TreeNode node) {
        if (node != null) {
            preorder(list, node.left);
            preorder(list, node.right);
            list.add(node.val);
        }
    }

    public List<Integer> iterator(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        TreeNode prev = null;
        while (!queue.isEmpty() || root != null) {
            while (root != null) {
                queue.push(root);
                root = root.left;
            }
            root = queue.pop();

            if (root.right == null || root.right == prev) {
                prev = root;
                list.add(root.val);
                root = null;
            } else {
                queue.push(root);
                root = root.right;
            }
        }
        return list;
    }
}
